package edu.pku.sei.sct.primitives;

import java.util.List;

import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;

import edu.pku.sei.ocl.evaluation.OCLVariable;
import edu.pku.sei.ocl.utilities.OCLStandardLibrary;
import edu.pku.sei.sct.evaluation.RuleContext;
import edu.pku.sei.sct.evaluation.SCTEnvironment;

public class ResolveContext extends AbstractPrimitive {
	static final public String ID = "ResolveContext";

	public ResolveContext(SCTEnvironment e) {
		super(e);
		// TODO Auto-generated constructor stub
	}

	/**
	 * argv[0] = context
	 */
	@Override
	public Object execute(Object... argv) {
		RuleContext rc = (RuleContext)argv[0];
		List<RuleContext> list = this.getSctEnvironment().getTransformationEnvironment().getTraces();
		EList<RuleContext> result = new BasicEList<RuleContext>();
		for(RuleContext c : list) {
			if(isContained(rc,c))
				result.add(c);
		}
		return result;
	}

	private boolean isContained(RuleContext rc, RuleContext c) {
		if(rc.getRule()!=c.getRule())
			return false;
		
		boolean flag = false;
		
		for(OCLVariable v : rc.getKey2value().keySet()){
			Object lv = rc.getValue(v);
			Object rv = c.getValue(v);
			
			if(OCLStandardLibrary.oclIsValid(lv)){
				flag = true; // there is at least one valid value in rc
				if(lv.equals(rv)==false)
					return false;
			}
		}
		
		return true && flag;
	}

	@Override
	public String getID() {
		// TODO Auto-generated method stub
		return ID;
	}

}
